package com.greyshark.lib.bluetooth.utils

class ModbusCrc16Utils {

    companion object{
        fun calculateModbusCRC16(data: ByteArray): ByteArray {
            var crc = 0xFFFF
            val polynomial = 0xA001

            for (byte in data) {
                crc = crc xor (byte.toInt() and 0xFF)
                for (i in 0 until 8) {
                    val lsb = crc and 0x0001
                    crc = crc shr 1
                    if (lsb != 0) {
                        crc = crc xor polynomial
                    }
                }
            }

            // 返回低字节在前的16位CRC值
            val crcInt =  ((crc and 0xFF) shl 8) or ((crc shr 8) and 0xFF)
            return byteArrayOf(
                (crcInt and 0xFF).toByte(), // 低字节
                ((crcInt shr 8) and 0xFF).toByte() // 高字节
            ).reversedArray()
        }
    }
}